package com.android.dumiaogou.fragment.group;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dumiaogou.R;
import com.android.dumiaogou.adapt.MyDateViewHolder;
import com.android.dumiaogou.fragment.BaseLazyFragment;
import com.android.dumiaogou.model.auction.AuctionHistoryData;
import com.android.dumiaogou.model.auction.AuctionHistoryDataCallback;
import com.android.dumiaogou.utils.ConstantsUrl;
import com.android.dumiaogou.utils.HttpUtils;
import com.android.dumiaogou.utils.MyLog;
import com.android.dumiaogou.utils.ObjectUtils;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.just.library.AgentWeb;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;
import okhttp3.Call;

import static com.alipay.sdk.app.statistic.c.v;

/**
 * Created by Administrator on 2017/9/1.
 */

public class Fragment_HistoryTrendingChart extends BaseLazyFragment {


    @BindView(R.id.mLinearLayout)
    FrameLayout mLinearLayout;
    @BindView(R.id.webView)
    WebView webView1;
    @BindView(R.id.progress)
    RelativeLayout progress;
    private ImageView htc_iv;
    private TextView htc_title;
    private TextView history_average_price;
    private TextView recently_turnovernumbers;
    private LineChartView lineChart;
    private FragmentActivity mcontext;
    private LayoutInflater inflater;
    private View view;
    private static final String ARG_PARAM1 = "param1";
    private String id;
    private String webUrl;
    AgentWeb agentweb;
    private String mParam1;
    private boolean networkConnected;
    private int page = 1;
    private float top;
    private AdaptList adapter;
    ArrayList<AuctionHistoryData.ListBean> listdata = new ArrayList<>();
    String[] periods;//X轴的标注
    float[] prices ;//图表的数据
    private List<PointValue> mPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisValues = new ArrayList<AxisValue>();
    private List<AxisValue> mAxisValuesy = new ArrayList<AxisValue>();
    public Fragment_HistoryTrendingChart() {


    }

    public static Fragment_HistoryTrendingChart newInstance(String webUrl) {
        Fragment_HistoryTrendingChart fragment = new Fragment_HistoryTrendingChart();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, v);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            webUrl = getArguments().getString(ARG_PARAM1);
        }
    }


    @Override
    protected void initPrepare() {

      //  ReFreshData();
    }


    /**
         * 初始化LineChart的一些设置
         */
       private void initLineChart(){

                Line line = new Line(mPointValues).setColor(Color.RED);  //折线的颜色
               List<Line> lines = new ArrayList<Line>();
              line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.SQUARE）
               line.setCubic(false);//曲线是否平滑
              line.setFilled(false);//是否填充曲线的面积
              line.setHasLabels(true);//曲线的数据坐标是否加上备注
               line.setHasLines(true);//是否用直线显示。如果为false 则没有曲线只有点显示
               line.setHasPoints(true);//是否显示圆点 如果为false 则没有原点只有点显示
              line.setStrokeWidth(1);
              lines.add(line);
              LineChartData data = new LineChartData();
           data.setBaseValue(Float.NEGATIVE_INFINITY);
           data.setValueLabelBackgroundEnabled(false);         //设置是否有数据背景
           data.setValueLabelsTextColor(Color.RED);           //设置数据文字颜色
           data.setValueLabelTextSize(8);                    //设置数据文字大小
       //   data.setValueLabelTypeface(Typeface.MONOSPACE);    //设置数据文字样式
           data.setLines(lines);
              //坐标轴
              Axis axisX = new Axis(); //X轴
             axisX.setHasTiltedLabels(true);
           axisX.setLineColor(Color.BLACK);
              axisX.setTextColor(Color.BLACK);  //设置字体颜色
              //axisX.setName("未来几天的天气");  //表格名称
                axisX.setTextSize(10);//设置字体大小
               axisX.setMaxLabelChars(7);  //最多几个X轴坐标
              axisX.setValues(mAxisValues);  //填充X轴的坐标名称
                data.setAxisXBottom(axisX); //x 轴在底部
        //      data.setAxisXTop(axisX);  //x 轴在顶部

           Axis axisY = new Axis();
           axisY.setHasLines(true);  //Y轴
           axisY.setLineColor(Color.BLACK);
               axisY.setMaxLabelChars(6); //默认是3，只能看最后三个数字
               //axisY.setName("温度");//y轴标注//设置字体大小
           axisY.setTextColor(Color.BLACK);
           axisY.setTextSize(10);
          // axisY.setValues( mAxisValuesy);
              data.setAxisYLeft(axisY);  //Y轴设置在左边
       //      data.setAxisYRight(axisY);  //y轴设置在右边
           data.setValueLabelBackgroundEnabled(true);//
              //设置行为属性，支持缩放、滑动以及平移
           //    lineChart.setInteractive(true);
            // lineChart.setZoomType(ZoomType.HORIZONTAL_AND_VERTICAL);
         //   lineChart.setContainerScrollEnabled(false, ContainerScrollType.HORIZONTAL);
              lineChart.setLineChartData(data);
           final Viewport v = new Viewport(lineChart.getMaximumViewport());
           v.left = 0;                             //坐标原点在左下
           v.bottom = 0;
           MyLog.e("dddsdtop",top+"");
           v.top = top;                            //最高点为
           v.right = 7 ;           //右边为点 坐标从0开始 点号从1 需要 -1
           lineChart.setMaximumViewport(v);   //给最大的视图设置 相当于原图
          // lineChart.setCurrentViewport(v);   //给当前的视图设置 相当于当前展示的图
            }
    /**
     * Y 轴的显示
     */
    private void getAxisLablesY(){
            for(float i = 0;i <=top; i+=top/6){
                mAxisValuesy.add(new AxisValue(i).setLabel(i+""));
            }
    }

            /**
          * X 轴的显示
          */
               private void getAxisLables(){
                for (int i = 0; i <periods.length; i++) {
                        mAxisValues.add(new AxisValue(i).setLabel(periods[i]));
                   }
           }

                /**
         * 图表的每个点的显示
         */
                private void getAxisPoints(){
               for (int i = 0; i < prices.length; i++) {
                       mPointValues.add(new PointValue(i, prices[i]));
                    }
           }

    @Override
    protected void onInvisible() {

    }


    @Override
    protected void initData() {

//        networkConnected = ObjectUtils.isNetworkConnected(getActivity());
//        if (networkConnected) {
//            GetDataComment(page, mParam1);
//        } else {
//           // ObjectUtils.GetDataNet(clickResetnetwork, progress, 4);
//        }

    }


    @Override
    protected View initView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
        this.inflater = inflater;
        view = inflater.inflate(R.layout.fragment_historytrendingchart_ry, container, false);
        mcontext = getActivity();
        ButterKnife.bind(this, view);
        agentweb = AgentWeb.with(this)//传入Activity or Fragment
                .setAgentWebParent(mLinearLayout, new LinearLayout.LayoutParams(-1, -1))//传入AgentWeb 的父控件 ，如果父控件为 RelativeLayout ， 那么第二参数需要传入 RelativeLayout.LayoutParams ,第一个参数和第二个参数应该对应。
                .useDefaultIndicator()// 使用默认进度条
                .createAgentWeb()//
                .ready()
                .go(webUrl);
//        initRecycle();
//        GetHistory();
        return view;
    }



    @OnClick(R.id.click_resetnetwork_refresh)
    public void onClick() {



    }





    private void  GetHistory() {

        String address = ConstantsUrl.domain + ConstantsUrl.ACUTIONREHISTORY;
        HashMap<String,String> map = new HashMap<>();
        map.put("page",page+"");
        map.put("size","20");
        map.put("auction_id",id);
        MyLog.e("地址", address);
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);

        if (networkConnected) {
            HttpUtils.get(address, map, new AuctionHistoryDataCallback() {
                @Override
                public void onError(Call call, Exception e, int id) {

                }
                @Override
                public void onResponse(AuctionHistoryData response, int id) {

                    if (response.getCode() == 0) {
                        listdata.clear();
                        if (response.getList() != null) {
                            top=Float.parseFloat(response.getList().get(0).getPrice());
                            periods = new String[response.getList().size()];
                            prices = new float[response.getList().size()];
                            for (int i = 0; i < response.getList().size(); i++) {
                                if(top<Float.parseFloat(response.getList().get(i).getPrice()))
                                {
                                    top = Float.parseFloat(response.getList().get(i).getPrice());
                                }
                                periods[i] = response.getList().get(i).getPeriod();
                                prices[i] = Float.parseFloat(response.getList().get(i).getPrice());
                                listdata.add(new AuctionHistoryData.ListBean(AuctionHistoryData.ListBean.THREE, response.getList().get(i).getId()
                                        , response.getList().get(i).getOrder_sn(), response.getList().get(i).getMid()
                                        ,  response.getList().get(i).getUsername(),response.getList().get(i).getC_time(), response.getList().get(i).getPrice()
                                        , response.getList().get(i).getMobile(), response.getList().get(i).getNickname()
                                        , response.getList().get(i).getC_time_format(), response.getList().get(i).getPhoto()
                                        , response.getList().get(i).getDiff(),response.getList().get(i).getPeriod()));
                            }
                            if (page == 1) {
                                adapter.setNewData(listdata);
                                ObjectUtils.photo2(mcontext,response.getAuction().getThumb(),htc_iv);
                                htc_title.setText(response.getAuction().getTitle());
                                history_average_price.setText(response.getAuction().getAvg_price());
                                if(response.getList().size()<20) {
                                    recently_turnovernumbers.setText("最新" + response.getList().size()+"期成交数");
                                }
                                else
                                {
                                    recently_turnovernumbers.setText("最新20期成交数");
                                }
                                getAxisLables();//获取x轴的标注
                                getAxisLablesY();
                                getAxisPoints();//获取坐标点
                                initLineChart();
                            } else {
                                adapter.addData(listdata);
                                adapter.loadMoreComplete();
                            }

                        } else {
                            adapter.loadMoreEnd();
                        }
                    } else {

                    }
                }
            });
        } else {
            if (page == 1) {

            }
            ObjectUtils.toast(getActivity(), "网络连接出现异常");
            adapter.loadMoreFail();

        }
    }
    public class AdaptList extends BaseMultiItemQuickAdapter<AuctionHistoryData.ListBean,MyDateViewHolder> {
        private String type;
        private FragmentActivity mcontext;
        private int limitposition;

        public AdaptList(FragmentActivity context, List<AuctionHistoryData.ListBean> data, String type) {
            super(data);
            this.mcontext = context;
            this.type = type;
            addItemType(AuctionHistoryData.ListBean.THREE, R.layout.item_htchart_ry);
        }


        @Override
        protected void convert(MyDateViewHolder holder,AuctionHistoryData.ListBean mainlistdata) {
            switch (holder.getItemViewType()) {
                case AuctionHistoryData.ListBean.THREE:
                    int time = Integer.parseInt(mainlistdata.getC_time());
                    long msl=(long)time*1000;
                    SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
                    SimpleDateFormat format2 = new SimpleDateFormat("HH:mm:ss");
                    String text = format1.format(msl);
                    String text1 = format2.format(msl);
                    holder.setText(R.id.aishang_datetime,text);
                    holder.setText(R.id.aishang_time,text1);
                    holder.setText(R.id.aishang_Firstname,mainlistdata.getUsername());
                    holder.setText(R.id.aishang_marketprice,"¥"+mainlistdata.getPrice());
                    if(mainlistdata.getDiff()!=null) {
                        float diff = Float.parseFloat(mainlistdata.getDiff());
                        if (diff > 0) {

                        } else {

                        }
                    }
                    break;

            }
        }
    }

}
